import BaseInput from "@/components/base/Input"
import { Props, Reg } from "@/components/form_item/formItemConfig"
import styled from "@emotion/styled"
import { memo, useEffect, useState } from "react"
import { useFormContext } from "react-hook-form"
import Svg from "../base/Svg"
const InputPassword = memo(
    ({
        fieldName,
        initValue,
        errorRegMsg,
        placeholder,
        required,
        showVerifyBox,
        showPlaceholder = true,
        className = "",
        style,
        onCustomError: onError,
    }: Props) => {
        const methods = useFormContext()
        const { register, resetField, watch, formState, getFieldState, clearErrors, setError } =
            methods
        const [showEye, setShowEye] = useState<boolean>(false)
        const [rule, setRule] = useState<{
            len: boolean
            letterNumber: boolean
            ruleReg: boolean
        }>({
            len: false,
            letterNumber: false,
            ruleReg: false,
        })
        const Clear = () => {
            setRule({
                len: false,
                letterNumber: false,
                ruleReg: false,
            })
            resetField(fieldName)
            clearErrors(fieldName)
        }
        const ChangeShowEye = () => {
            setShowEye(!showEye)
        }
        const values = watch(fieldName) ?? initValue
        const errorsName = formState.errors[fieldName]
        const FieldState = getFieldState(fieldName, formState)
        useEffect(() => {
            let _rule = rule
            if (values && Reg.letterAndNumberReg.test(values)) {
                _rule = {
                    ..._rule,
                    ...{ letterNumber: true },
                }
            } else {
                _rule = {
                    ..._rule,
                    ...{ letterNumber: false },
                }
            }

            if (values && Reg.passwordReg.test(values)) {
                _rule = {
                    ..._rule,
                    ...{ ruleReg: true },
                }
            } else {
                _rule = {
                    ..._rule,
                    ...{ ruleReg: false },
                }
                setError(fieldName, {
                    message: errorRegMsg || " must contain at least 1 letter and 1 number",
                    type: "pattern",
                })
                onError?.(fieldName, errorRegMsg || "Password Error")
            }

            if (values && values?.length > 7 && values?.length < 21) {
                _rule = {
                    ..._rule,
                    ...{ len: true },
                }
            } else {
                _rule = {
                    ..._rule,
                    ...{ len: false },
                }
                setError(fieldName, {
                    message: "Password minLength is 8, maxLength is 20",
                    type: "maxLength",
                })
                onError?.(fieldName, "Password minLength is 8, maxLength is 20")
            }
            setRule(_rule)
            if (_rule.len && _rule.ruleReg && _rule.letterNumber) {
                clearErrors(fieldName)
            }
            // eslint-disable-next-line react-hooks/exhaustive-deps
        }, [values])
        const showError = (errorsName?.message || !rule.ruleReg) && FieldState.isDirty
        return (
            <InputItem
                className={`
                    ${showError ? " error " : " "} 
                    ${values! ? " showClearIcon " : ""}
                    ${showVerifyBox ? " showVerifyBox " : ""}
                    ${showPlaceholder ? " placeholderBox " : ""}
                    ${className}
                `}
            >
                <BaseInputs
                    id={"inputPassword-" + fieldName}
                    type={showEye ? "text" : "password"}
                    style={style}
                    maxLength={20}
                    {...register(fieldName, {
                        required: {
                            message: `${fieldName} is required`,
                            value: required ?? true,
                        },
                        maxLength: {
                            value: 20,
                            message: "Password maxLength is 20",
                        },
                        pattern: {
                            value: Reg.passwordReg,
                            message: errorRegMsg || "must contain at least 1 letter and 1 number",
                        },
                        value: initValue,
                    })}
                />
                {showPlaceholder && (
                    <InputLabel
                        className="inputTitle"
                        htmlFor={"inputPassword-" + fieldName}
                    >
                        {placeholder ?? "Password"}
                    </InputLabel>
                )}
                <CleanInputBox
                    className="cleanIcon"
                    onClick={Clear}
                >
                    {showError ? (
                        <Svg src={"components/form_item/clear_text_red_icon.svg"} />
                    ) : (
                        <Svg src={"components/form_item/clear_text_icon.svg"} />
                    )}
                </CleanInputBox>
                <EyeIcon
                    className={`${showEye ? "" : "closeEye"}`}
                    onClick={ChangeShowEye}
                >
                    {showEye ? (
                        <Svg src={"components/form_item/eye_open_icon.svg"} />
                    ) : (
                        <Svg src={"components/form_item/eye_close_icon.svg"} />
                    )}
                </EyeIcon>
                {errorsName && (
                    <VerifyMessage>
                        <em>
                            <Svg src={"components/form_item/public_fail_icon.svg"} />
                        </em>
                        {errorsName?.message as string}
                    </VerifyMessage>
                )}
                {showVerifyBox && (
                    <VerifyBox>
                        <h4>The password must contain at least</h4>
                        <p className={`rule ${rule.len ? "green" : ""}`}>8-20 characters</p>
                        <p className={`rule ${rule.letterNumber ? "green" : ""}`}>
                            1 letter and 1 number
                        </p>
                    </VerifyBox>
                )}
            </InputItem>
        )
    },
)

export default InputPassword

const InputItem = styled.div`
    position: relative;
    display: flex;

    &.showVerifyBox {
        flex-direction: column;
    }

    &.showClearIcon span {
        display: inline-block;
    }

    &.clearItem span.cleanIcon {
        right: 16rem;
    }

    &.showClearIcon .inputTitle {
        top: 8rem;
        font-size: 12rem;
        line-height: 16rem;
        color: #6a7081;
    }

    &.placeholderBox input {
        height: 56rem;
        padding-top: 24rem;
    }

    &.placeholderBox input:focus + label,
    &.placeholderBox.showClearIcon .inputTitle {
        top: 8rem;
    }

    &.placeholderBox span {
        top: 16rem;
    }

    &.error p {
        display: block;
    }

    &.error input {
        border-color: #fb2d60;
        background-color: #fee0e7;
    }

    &.error label.inputTitle {
        color: #fb2d60;
    }
`

const BaseInputs = styled(BaseInput)`
    background-color: #f3f3f7;
    outline: none;
    border-radius: 8rem;
    border: 1rem solid #bbbdcc;
    height: 48rem;
    width: 100%;
    color: #3e4046;
    font-family: "Gilroy", sans-serif;
    padding-left: 16rem;

    &:focus {
        outline: none;
        border-color: #165dff;
    }

    &:focus + label {
        top: 0;
        font-size: 12rem;
        line-height: 16rem;
    }
`

const InputLabel = styled.label`
    position: absolute;
    top: 16rem;
    left: 16rem;
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 16rem;
    line-height: 24rem;
    letter-spacing: 0;
    color: #9ca3b4;
    transition:
        top 0.18s linear,
        font-size 0.18s linear;
`

const CleanInputBox = styled.span`
    display: none;
    position: absolute;
    top: 12rem;
    right: 16rem;
    z-index: 10;
    width: 24rem;
    height: 24rem;

    &.cleanIcon {
        right: 45rem;
    }
`

const EyeIcon = styled.span`
    position: absolute;
    top: 12rem;
    right: 16rem;
    z-index: 10;
    width: 24rem;
    height: 24rem;
    line-height: 30rem;
    text-align: center;
`

const VerifyMessage = styled.p`
    display: none;
    position: absolute;
    bottom: -32rem;
    left: 0;
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 12rem;
    line-height: 16rem;
    letter-spacing: 0;
    color: #fb2d60;
    padding-left: 20rem;

    & > em {
        position: absolute;
        display: block;
        width: 16rem;
        height: 16rem;
        top: 0;
        left: 0;
        line-height: normal;
        text-align: center;
    }

    &.stepNextvm {
        display: block;
        position: initial;
        margin: 0;
        padding: 0;
    }

    &.stepNextvm::before {
        display: none;
    }

    &.codemsg {
        position: relative;
        margin: 0;
        bottom: -4rem;
        left: 0;
    }

    &.codemsg.error {
        display: block;
    }
`

const VerifyBox = styled.div`
    padding-top: 12rem;

    & h4 {
        font-family: "Gilroy", sans-serif;
        font-weight: 500;
        font-size: 14rem;
        line-height: 20rem;
        letter-spacing: 0;
        color: #131416;
        margin: 0;
    }

    & p {
        font-family: "Gilroy", sans-serif;
        font-weight: 400;
        font-size: 14rem;
        line-height: 20rem;
        letter-spacing: 0;
        color: #69728c;
        margin: 0;

        &.green {
            color: #00b42a;
        }
    }
`
